package com.vipboot.framework.social.autoconfig;

import com.vipboot.framework.social.core.cache.AuthRedisStateCache;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.cache.AuthDefaultStateCache;
import me.zhyd.oauth.cache.AuthStateCache;
import org.redisson.client.RedisClient;
import org.redisson.spring.starter.RedissonAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;


@Slf4j
public class AuthStateCacheConfig {

    /**
     * Redis 缓存
     */
    @ConditionalOnMissingBean(AuthStateCache.class)
    @ConditionalOnClass(RedisClient.class)
    @AutoConfigureBefore(RedissonAutoConfiguration.class)
    @ConditionalOnProperty(name = "justauth.cache.type", havingValue = "redis", matchIfMissing = true)
    public static class Redis {
        static {
            log.debug("JustAuth 使用 Redis 缓存存储 state 数据");
        }

        @Bean
        public AuthStateCache authStateCache() {
            return new AuthRedisStateCache();
        }
    }

    /**
     * 默认缓存
     */
    @ConditionalOnMissingBean(AuthStateCache.class)
    @ConditionalOnProperty(name = "justauth.cache.type", havingValue = "default", matchIfMissing = true)
    static class Default {
        static {
            log.debug("JustAuth 使用 默认缓存存储 state 数据");
        }

        @Bean
        public AuthStateCache authStateCache() {
            return AuthDefaultStateCache.INSTANCE;
        }
    }


    /**
     * 默认缓存
     */
    @ConditionalOnProperty(name = "justauth.cache.type", havingValue = "custom")
    static class Custom {
        static {
            log.debug("JustAuth 使用 自定义缓存存储 state 数据");
        }

        @Bean
        @ConditionalOnMissingBean(AuthStateCache.class)
        public AuthStateCache authStateCache() {
            log.error("请自行实现 me.zhyd.oauth.cache.AuthStateCache");
            throw new RuntimeException();
        }
    }

}
